import React from 'react';
import ReactDOM from 'react-dom';
import Component from './component/Component.js';
import Relay from "react-relay";
import EventManager from './component/util/EventManager'
process.env.NODE_ENV = 'production';
import {hashHistory,Link} from 'react-router';
import  Config from "./component/util/Config"
var AES = require("crypto-js/aes");
var CryptoJS = require("crypto-js");

const IsDevelopment = true;

const mkey = CryptoJS.enc.Utf8.parse("<>hj12@#$$%^~~ff");

function injectNetworkLayer() {
    var myNetworkLayer = {
        sendMutation: checkNetInfoAndSendMutation,
        sendQueries(queryRequests) {
        },
        supports(...options) {


        },
    };

    Relay.injectNetworkLayer(
        myNetworkLayer
    );
}

async function checkNetInfoAndSendMutation(mutationRequest) {
    let uid = sessionStorage.getItem('uid');
    let token =  sessionStorage.getItem('token');
    let systemRoleId =  sessionStorage.getItem('systemRoleId');
    mutationRequest._mutation.__variables__.input.argsInput['uid']=uid;
    mutationRequest._mutation.__variables__.input.argsInput['token']=token;
    mutationRequest._mutation.__variables__.input.argsInput['systemRoleId']=systemRoleId;
    mutationRequest._mutation.__variables__.input.argsInput['systemtype']='1';
    let body = JSON.stringify({
        query: mutationRequest.getQueryString(),
        variables: mutationRequest.getVariables()
    });

    if(!IsDevelopment){
        let mm = await CryptoJS.AES.encrypt(body,mkey,{
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        body = mm.ciphertext.toString();
    }
    return fetch(Config.url, {
        method: 'POST',
        headers: {
            'Accept': '*/*',
            'Content-Type': 'application/json',
        },
        body: body
    }).then(function (result) {
        return result.json();
    }).then((async (result) => {
        if (result.errors) {
            mutationRequest.reject();
        } else {
            if(result.error !==undefined){
                if(result.error =='TOKEN_ERROR'||result.error ==  'TOKEN_NOT_INVALID'){
                    mutationRequest.reject();
                    hashHistory.push('/');
                    EventManager.emitter('islogin',false);
                    alert('令牌错误');
                }
            }
            if(!IsDevelopment){
                let encryptedHexStr = CryptoJS.enc.Hex.parse(result.data);
                let encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
                let decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, mkey, {
                    mode: CryptoJS.mode.ECB,
                    padding: CryptoJS.pad.Pkcs7
                });
                let decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);
                mutationRequest.resolve({response: JSON.parse(decryptedStr)});
            }else{
                mutationRequest.resolve({response: result.data});
            }
        }
    }).bind(this)).catch(((error) => {
        mutationRequest.reject();
    }).bind(this));
}

injectNetworkLayer();




ReactDOM.render(<Component />, document.getElementById('app'));
